package com.ymatou.iapi.trading.operate.parameter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.proditem.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.trading.operate.parameter.enums.AppTerminalSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.OrderSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.OrderTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.PriceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.ProductRefundChannelEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.PromotionTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.SalesTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.SellerCouponApplianceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.StockStatusEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.TerminalSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.YmatouCouponApplianceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.po.SubcatalogsPo;
import com.ymatou.iapi.trading.operate.parameter.req.BizVo;
import com.ymatou.iapi.trading.operate.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.trading.operate.service.PlaceOrderCall;
import com.ymatou.iapi.userservice.parameter.resp.AddressResp;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.CouponCallService;
import com.ymttest.business.service.JUserCallService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.SellerProductCallService;
import com.ymttest.common.enums.CancelOrderTypeEnum;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class PlaceOrderService {

	public static LogisticsTypeEnum logisticsType = LogisticsTypeEnum.PackageDelivery;

	/**
	 * 
	 * 创建砍价团订单 开团订单
	 * 
	 * @param bizId
	 *            砍价团id bizId=null,随机生成一个砍价团id
	 *
	 */
	public static PlaceOrderResp placeOrder1(String bizId) {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		// 创建砍价团订单
		BizVo bizVo = new BizVo();
		// 砍价团id
		if (bizId == null) {
			bizId = TestDataManager.getRandomNum(9);
		}
		// String bizId=
		// 1:砍价团
		int bizType = 1;
		// 砍价团(1 开团, 2 参团)
		Integer bizSubType = 1;

		bizVo.setBizId(bizId);
		bizVo.setBizType(bizType);
		bizVo.setBizSubType(bizSubType);

		placeorderBean.setBizSource(bizVo);

		placeorderBean
				.getOrderGroups()
				.get(0)
				.getOrders()
				.get(0)
				.setReceiveName("砍价团开团操作人" + TestDataManager.getRandomIntNum(8));

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0)
				.setProductName("砍价团开团订单" + TestDataManager.getRandomIntNum(5));
		// 砍价团拼邮
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0)
				.setLogisticsType(LogisticsTypeEnum.PackageDelivery);

		PlaceOrderResp placeOrderResp = callPlaceOrderService(placeorderBean);

		placeOrderResp.setBizId(bizId);

		return placeOrderResp;

	}

	/**
	 * 
	 * 创建砍价团订单 参团订单
	 *
	 * @param bizId
	 *            砍价团团id
	 */
	public static PlaceOrderResp placeOrder2(String bizId) {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		// 创建砍价团订单
		BizVo bizVo = new BizVo();
		// 砍价团id
		// String bizId=bizId;
		// 1:砍价团
		int bizType = 1;
		// 砍价团(1 开团, 2 参团)
		Integer bizSubType = 2;

		bizVo.setBizId(bizId);
		bizVo.setBizType(bizType);
		bizVo.setBizSubType(bizSubType);

		placeorderBean.setBizSource(bizVo);

		placeorderBean
				.getOrderGroups()
				.get(0)
				.getOrders()
				.get(0)
				.setReceiveName("砍价团参团操作人" + TestDataManager.getRandomIntNum(8));
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0)
				.setProductName("砍价团参团订单" + TestDataManager.getRandomIntNum(5));

		// 砍价团拼邮
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0)
				.setLogisticsType(LogisticsTypeEnum.PackageDelivery);

		PlaceOrderResp placeOrderResp = callPlaceOrderService(placeorderBean);

		placeOrderResp.setBizId(bizId);

		return placeOrderResp;

	}

	/**
	 * 
	 * 一次下单同 一个商家 2个订单号,分别使用平台,商家优惠券,每个订单下面3个商品
	 * 
	 */
	public static PlaceOrderResp placeOrder3() {

		PlaceOrderReq placeorderBean = new PlaceOrderReq();

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId2"));

		placeorderBean = getDefaultOrderReq();

		List<OrderGroupVo> orderGroupVoList = new ArrayList<OrderGroupVo>();

		OrderGroupVo orderGroupVo = getDefaultOrderGroupVo(userId, sellerId);

		orderGroupVo.getOrders().add(getDefaultOrderVo(userId));

		// 商家优惠券
		BigDecimal sellerCouponValue = new BigDecimal(17);
		String sellerCouponCode = null;
		try {
			sellerCouponCode = new CouponCallService().receiveCouponInfo(
					sellerId, userId, sellerCouponValue);
		} catch (Exception e) {
			Logger.debug("创建商家优惠券失败！");
			e.printStackTrace();
		}

		SellerCouponVo sellerCoupon = new SellerCouponVo();

		sellerCoupon.setApplianceType(SellerCouponApplianceTypeEnum.ALL);
		sellerCoupon.setCouponCode(sellerCouponCode);
		sellerCoupon.setCouponValue(sellerCouponValue);

		orderGroupVo.setSellerCoupon(sellerCoupon);

		if (null == sellerCouponCode)
			orderGroupVo.setSellerCoupon(null);

		orderGroupVoList.add(orderGroupVo);

		// 每个订单项下面再添加2个商品，一共是3个商品
		for (int i = 0; i < 2; i++) {
			orderGroupVoList
					.get(0)
					.getOrders()
					.forEach(
							order -> order.getOrderItems().add(
									getDefaultOrderItemVo()));
		}

		// 设置订单商家组
		placeorderBean.setOrderGroups(orderGroupVoList);

		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 
	 * 一次下单同一个商家1个订单分别使用平台,商家优惠券,订单下面2个商品
	 * 
	 */
	public static PlaceOrderResp placeOrder4() {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		OrderItemVo orderitem2 = getDefaultOrderItemVo();

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(orderitem2);

		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 
	 * 
	 * 一次下单同一个商家1个订单分别使用平台,商家优惠券,订单下面1个商品
	 *
	 */
	public static PlaceOrderResp placeOrder5() {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		return callPlaceOrderService(placeorderBean);

	}

	/**
	 * 
	 * 一次下单同一个商家1个订单,包含2个商品 不使用优惠券
	 * 
	 */
	public static PlaceOrderResp placeOrderWithOutCoupon() {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		// 不使用平台券
		placeorderBean.setYmatouCoupon(null);
		// 不使用商家券
		placeorderBean.getOrderGroups().get(0).setSellerCoupon(null);

		OrderItemVo orderitem2 = getDefaultOrderItemVo();

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(orderitem2);

		/*
		 * //设置物流方式 placeorderBean.getOrderGroups().get(0).getOrders().get(0)
		 * .getOrderItems() .forEach(item ->
		 * item.setLogisticsType(logisticsType));
		 */

		return callPlaceOrderService(placeorderBean);

	}

	/**
	 * 
	 * 一次下单同一个商家1个订单分别使用平台,商家优惠券,订单下面2个商品 不使用优惠券
	 */
	public static PlaceOrderResp placeOrderWithOutCoupon(Integer userId) {

		PlaceOrderReq placeorderBean = getDefaultOrderReq(userId);

		// 不使用平台券
		placeorderBean.setYmatouCoupon(null);
		// 不使用商家券
		placeorderBean.getOrderGroups().get(0).setSellerCoupon(null);

		OrderItemVo orderitem2 = getDefaultOrderItemVo();

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(orderitem2);

		// 设置物流方式
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems()
				.forEach(item -> item.setLogisticsType(logisticsType));

		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 
	 * 根据传过来的 买家id,product信息 创建订单
	 * 
	 * @param SaveOrderReq
	 * @return PlaceOrderResp
	 */
	public static PlaceOrderResp saveOrder(SaveOrderReq saveOrderReq) {

		int userId = saveOrderReq.getUserId();

		List<ProReq> proList = saveOrderReq.getProReqList();

		List<OrderGroupVo> orderGroupVoList = new ArrayList<OrderGroupVo>();

		for (ProReq pro : proList) {

			String productId = pro.getProductId();
			String catalogId = pro.getCatalogId();
			int productNum = pro.getProductNum();

			OrderItemVo orderItemVo = SellerProductCallService.getOrderItemVo(
					productId, catalogId);

			orderItemVo.setProductNum(productNum);

			orderItemVo.setOriginalPrice(orderItemVo.getProductPrice());

			orderItemVo.setEarnestPrice(orderItemVo.getProductPrice());

			orderItemVo.setSalesType(SalesTypeEnum.Live);

			int sellerId = orderItemVo.getSellerId();

			//
			boolean isExist = false;
			try {
				isExist = orderGroupVoList.stream().anyMatch(
						g -> g.getSellerId() == sellerId);
			} catch (Exception e) {
				// TODO: handle exception

			}
			OrderGroupVo orderGroupVo = null;

			if (isExist) {

				for (OrderGroupVo group : orderGroupVoList) {

					if (group.getSellerId() == sellerId) {

						group.getOrders().get(0).getOrderItems()
								.add(orderItemVo);
					}

				}

			} else {

				orderGroupVo = getDefaultOrderGroupVo(userId, sellerId);

				List<OrderItemVo> orderItemList = new ArrayList<OrderItemVo>();

				orderItemList.add(orderItemVo);

				orderGroupVo.getOrders().get(0).setOrderItems(orderItemList);
			}
			if (orderGroupVo != null) {
				orderGroupVoList.add(orderGroupVo);
			}

		}

		PlaceOrderReq placeorderBean = new PlaceOrderReq();

		placeorderBean.setRequestId(TestDataManager.getRandomUUID().toString());
		placeorderBean.setTerminalSource(TerminalSourceEnum.IOS);
		placeorderBean.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		placeorderBean.setDeviceId(TestDataManager.getRandomUUID().toString());

		// placeorderBean.setDeviceId("1392F700-8429-481C-9589-8957582C49E0");

		placeorderBean.setOrderSource(OrderSourceEnum.PC);

		placeorderBean.setAppId("autotest");

		placeorderBean.setUserId(userId);

		// 不使用平台优惠券
		placeorderBean.setYmatouCoupon(null);

		placeorderBean.setOrderGroups(orderGroupVoList);

		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 
	 * 根据物流方式创建订单 不使用优惠券
	 * 
	 * @logisticsType 物流枚举类型
	 *                com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum
	 * 
	 */
	public static PlaceOrderResp placeOrderBylogisticsType(
			LogisticsTypeEnum logisticsType) {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		// 不使用平台券
		placeorderBean.setYmatouCoupon(null);
		// 不使用商家券
		placeorderBean.getOrderGroups().get(0).setSellerCoupon(null);

		// OrderItemVo orderitem2 = getDefaultOrderItemVo();

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setLogisticsType(logisticsType);

		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 
	 * 一次下单同 一个商家 2个订单号,每个订单下面3个商品,商品不包邮，随机运费
	 * 
	 */
	public static PlaceOrderResp placeOrder7() {

		PlaceOrderReq placeorderBean = new PlaceOrderReq();

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		placeorderBean = getDefaultOrderReq();

		List<OrderGroupVo> orderGroupVoList = new ArrayList<OrderGroupVo>();

		OrderGroupVo orderGroupVo = getDefaultOrderGroupVo(userId, sellerId);

		orderGroupVo.getOrders().add(getDefaultOrderVo(userId));

		orderGroupVoList.add(orderGroupVo);

		// 每个订单项下面再添加2个商品，一共是3个商品
		for (int i = 0; i < 2; i++) {
			orderGroupVoList
					.get(0)
					.getOrders()
					.forEach(
							order -> order.getOrderItems().add(
									getDefaultOrderItemVo()));
		}

		// 设置订单商家组
		placeorderBean.setOrderGroups(orderGroupVoList);

		// 设置没有商品的随机运费
		for (int i = 0; i < 1; i++) {

			for (int j = 0; j < placeorderBean.getOrderGroups().get(i)
					.getOrders().size(); j++) {

				placeorderBean
						.getOrderGroups()
						.get(i)
						.getOrders()
						.get(j)
						.getOrderItems()
						.forEach(
								item -> item.setFreight(new BigDecimal(
										new Random().nextInt(50))));

			}

		}

		// 注意该方法，会返回一个固定大小list，不运行后续 add
		// Arrays.asList(a)
		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 
	 * 一次下单同 一个商家 2个订单号,不使用优惠券,每个订单下面3个商品,商品不包邮，第二个商品运费为0
	 * 
	 */
	public static PlaceOrderResp placeOrder8() {

		PlaceOrderReq placeorderBean = new PlaceOrderReq();

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		placeorderBean = getDefaultOrderReq();

		List<OrderGroupVo> orderGroupVoList = new ArrayList<OrderGroupVo>();

		OrderGroupVo orderGroupVo = getDefaultOrderGroupVo(userId, sellerId);

		orderGroupVo.getOrders().add(getDefaultOrderVo(userId));

		orderGroupVoList.add(orderGroupVo);

		// 每个订单项下面再添加2个商品，一共是3个商品
		for (int i = 0; i < 2; i++) {
			orderGroupVoList
					.get(0)
					.getOrders()
					.forEach(
							order -> order.getOrderItems().add(
									getDefaultOrderItemVo()));
		}

		// 设置订单商家组
		placeorderBean.setOrderGroups(orderGroupVoList);

		// 设置商品的随机运费
		for (int i = 0; i < 1; i++) {

			for (int j = 0; j < placeorderBean.getOrderGroups().get(i)
					.getOrders().size(); j++) {

				placeorderBean
						.getOrderGroups()
						.get(i)
						.getOrders()
						.get(j)
						.getOrderItems()
						.forEach(
								item -> item.setFreight(new BigDecimal(
										new Random().nextInt(50))));

			}

		}

		// 第二个商品包邮，运费为0
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(1).setFreight(BigDecimal.ZERO);

		return callPlaceOrderService(placeorderBean);
	}

	/**
	 * 创建商品
	 * 
	 * @param stockNum
	 * @return
	 */
	public static JSONObject creaderPro(int stockNum) {

		String sellerName = String.valueOf(EnvSetup.getData("SellerName"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId2"));
		return creaderPro(sellerName, sellerId, stockNum);

	}

	/**
	 * 创建商品
	 * {"ThirdCategoryId":1003,"LocalReturn":1,"SellOutActivity":null,"SizePicList":[],"ProductId":"b8bc56e0-0252-420d-ba42-5cb19d95654b","ProdId":206029311,"BrandId":10145,"BrandName":"","TariffType":0,"IsPspProduct":false,"Version":"1.001","ValidStart":"2017-10-25T15:29:04","PicList":["http://pc1.img.ymatou.com/G01/shangou/M00/2A/17/rBBlD1eqnq-AEvUHAANhqAY9_CQ839_n_w_o.jpg"],"CountryId":0,"Status":0,"BrandEnName":"IBM","ProductCode":"shangpinhuohao123456","OwnProduct":false,"NewStartTime":"2017-10-25T15:29:04","BondedArea":0,"Grade":"C","AddTime":"2017-10-25T15:29:04","LimitNum":0,"Weight":0,"IsNewProduct":true,"ThirdCategoryName":"按键手机","ExtraDeliveryType":0,"CatalogType":0,"NextActivity":null,"Introduction":"自动化测试 发布商品","Video":null,"IsFreeShipping":true,"IsHotRecmd":false,"CategoryId":1002,"HasTextDescription":true,"WeightUnit":0,"NoReasonReturn":false,"NoticeRisk":true,"NewEndTime":"2017-11-01T15:29:04","MasterCategoryId":1001,"LimitNumStartTime":"1900-01-01T00:00:00","SellerId":3791677,"ExtraDeliveryFee":0,"ProductActivity":null,"DeliveryMethod":2,"Title":"自动化测试_立即上架商品 10-25 15:28:59","CatalogList":[{"VipPrice":9,"CatalogStock":10,"IsExtraDelivery":false,"NextActivityPrice":0,"CatalogId":"8f76b35e-fe15-4a24-9155-01bd479e105d","Weight":0,"NextActivityStock":0,"ActivityPrice":0,"PropertyList":[{"Value":null,"Sort":0,"PicUrl":null,"Name":null}],"ActivityStock":0,"IsPackage":false,"Price":10,"NewGuestPrice":8,"SKU":"shangpinbianma123456","IsPreSale":false,"IsInActivity":false}],"DeliveryTemplateList":[],"LiveProduct":null,"MasterCategoryName":"手机数码、电脑","CategoryName":"手机通讯","ValidEnd":"2017-11-01T15:29:04","SellerName":"wreqwrqw"}
	 * @param sellerName
	 * @param sellerId
	 * @param stockNum
	 * @return
	 */
	public static JSONObject creaderPro(String sellerName, int sellerId,
			int stockNum) {

		Map updateMap = new HashMap();

		updateMap.put("Product->Catalogs[0]->Num", stockNum);

		JSONObject productInfo = null;

		try {

			String proId = SellerProductCallService
					.addNewProductOnSale(sellerId, sellerName, updateMap)
					.getJSONObject("Data").getString("ProductID");

			productInfo = GetProductInfoByProductIdCall
					.GetProductInfoByProductId(proId).getJSONObject("Data")
					.getJSONObject("Product");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return productInfo;

	}
	public static String getNewProductId(String sellerName, int sellerId,
			int stockNum) {
		Map updateMap = new HashMap();

		updateMap.put("Product->Catalogs[0]->Num", stockNum);
		String proId = "";
		try {

			proId = SellerProductCallService
					.addNewProductOnSale(sellerId, sellerName, updateMap)
					.getJSONObject("Data").getString("ProductID");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return proId;

	}
	/**
	 * 
	 * 下单，由交易库存扣库存
	 *
	 */
	public static PlaceOrderResp placeOrder9() {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		JSONObject pro = creaderPro(100);

		OrderItemVo OrderItemVo = placeorderBean.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);

		try {

			String productVer = pro.getString("Version");

			OrderItemVo.setProductVer(productVer);

			OrderItemVo.setProductId(pro.getString("ProductId"));

			OrderItemVo.setCatalogId(pro.getJSONArray("CatalogList")
					.getJSONObject(0).getString("CatalogId"));

		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 由交易扣库存
		placeorderBean.setNeedsReduceStock(true);

		return callPlaceOrderService(placeorderBean);

	}

	/**
	 * 
	 * 下单含有组合商品，使用优惠券，商家优惠
	 *
	 */
	public static PlaceOrderResp placeOrder10() {

		PlaceOrderReq placeorderBean = getDefaultOrderReq();

		try {

			SubcatalogsPo subcatalogsPo = new YmtProductsIWapper()
					.getSubcatalogs();

			SubcatalogsPo subcatalogsPo2 = new YmtProductsIWapper()
					.getSubcatalogs();

			// 组合商品
			String catalogId = subcatalogsPo.getCatalogId();

			placeorderBean = PlaceOrderService.getDefaultOrderReq();

			OrderItemVo OrderItemVo = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0);

			OrderItemVo.setCatalogId(catalogId);

			OrderItemVo.setSubProduct(true);

			OrderItemVo.setFreight(new BigDecimal(new Random().nextInt(100)));

			OrderItemVo OrderItemVo2 = PlaceOrderService
					.getDefaultOrderItemVo();

			OrderItemVo2.setCatalogId(subcatalogsPo2.getCatalogId());

			OrderItemVo2.setFreight(new BigDecimal(new Random().nextInt(100)));

			OrderItemVo2.setSubProduct(true);

			OrderItemVo2.setPspProduct(true);

			OrderItemVo2.setPreSale(true);

			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().add(OrderItemVo2);

			// 定义买手下的优惠商品信息list
			List<SellerPromotionVo> sellerPromotionList = new ArrayList<SellerPromotionVo>();

			SellerPromotionVo sellerPromotion1 = new SellerPromotionVo();
			sellerPromotion1.setAmountCondition(new BigDecimal(20));
			sellerPromotion1.setId(123456789);
			sellerPromotion1.setName("自动化商家优惠活动");
			Set<String> productList = new HashSet<String>();
			productList.add(OrderItemVo.getProductId());
			sellerPromotion1.setProductIds(productList);
			sellerPromotion1.setPromotionValue(new BigDecimal(12));
			sellerPromotion1.setQtyCondition(4);
			sellerPromotion1.setReducedAmount(new BigDecimal(15));
			sellerPromotion1.setType(PromotionTypeEnum.DiscountIfCountEnough);

			sellerPromotionList.add(sellerPromotion1);

			placeorderBean.getOrderGroups().get(0)
					.setSellerPromotions(sellerPromotionList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return callPlaceOrderService(placeorderBean);

	}

	public static PlaceOrderResp callPlaceOrderService(
			PlaceOrderReq placeorderBean) {

		PlaceOrderCall placeorderCall = new PlaceOrderCall();

		PlaceOrderResp orderResp = new PlaceOrderResp();

		placeorderCall.setData(false, placeorderBean);

		try {

			placeorderCall.callService();

			int userId = placeorderBean.getUserId();

			int sellerId = placeorderBean.getOrderGroups().get(0).getSellerId();

			JSONArray orderArray = placeorderCall.getOrderIds();

			List<Order> orderList = new ArrayList<Order>();

			for (int i = 0; i < orderArray.length(); i++) {

				Order order = new Order();
				int orderId = orderArray.getInt(i);

				List<Map> maps = new DefaultWapper()
						.executeSql("select iBuyerId,fFreight from ymt_orders where iOrderId="
								+ orderId);

				order.setOrderId(orderId);
				order.setSellerId(sellerId);

				order.setSellerId((Integer) maps.get(0).get("iBuyerId"));
				order.setFreight((BigDecimal) maps.get(0).get("fFreight"));

				List<OrderInfoPo> orderInfoList = new DefaultWapper()
						.selectOrderInfoByOrderId2(orderId);

				order.setOrderInfoList(orderInfoList);

				orderList.add(order);
			}

			int tradingId = placeorderCall.getTradingId();
			// 根据交易号计算需要支付的金额
			BigDecimal payAmount = new OrderCallService()
					.getNeedPrePayAmountOfCashBymainOrderId(tradingId);

			orderResp.setTradingId(tradingId);
			orderResp.setOrderList(orderList);
			orderResp.setPayAmount(payAmount);
			orderResp.setUserId(userId);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return orderResp;

	}

	/*
	 * 构造默认的请求 买手组 OrderGroupVo
	 */
	public static OrderGroupVo getDefaultOrderGroupVo(Integer userId,
			Integer sellerId) {

		OrderGroupVo orderGroupVo = new OrderGroupVo();

		if (null == sellerId)
			sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		if (null == userId)
			userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));

		orderGroupVo.setSellerId(sellerId);

		// 构造默认的请求 OrderVO
		List<OrderVo> orderVoList = new ArrayList<OrderVo>();

		orderVoList.add(getDefaultOrderVo(userId));

		orderGroupVo.setOrders(orderVoList);

		/*		// 商家优惠券
				BigDecimal sellerCouponValue = new BigDecimal(15);

				SellerCouponVo sellerCoupon = new SellerCouponVo();

				String sellerCouponCode = null;
				try {
					sellerCouponCode = new CouponCallService().receiveCouponInfo(
							sellerId, userId, sellerCouponValue);

				} catch (Exception e) {
					Logger.debug("创建商家优惠券失败！");
					// e.printStackTrace();

				}

				sellerCoupon.setApplianceType(SellerCouponApplianceTypeEnum.ALL);
				sellerCoupon.setCouponCode(sellerCouponCode);
				sellerCoupon.setCouponValue(sellerCouponValue);

				if (sellerCouponCode == null || sellerCouponCode.isEmpty()) {

					sellerCoupon = null;

				}*/

		// 商家优惠券
		orderGroupVo.setSellerCoupon(null);
		// 商家优惠
		orderGroupVo.setSellerPromotions(null);

		return orderGroupVo;
	}

	/*
	 * 构造默认的请求订单请求 OrderVo
	 */
	public static OrderVo getDefaultOrderVo(Integer userId) {
		OrderVo orderVo = new OrderVo();
		AddressResp add = null;
		if (null == userId)
			userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));

		try {
			add = JUserCallService.getAddressInfoList(userId).get(0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Logger.info(userId + ": 获取用户地址信息出错！#############################");
			return null;
		}
		// 现货
		orderVo.setOrderType(OrderTypeEnum.Spot);
		// 全款订单
		orderVo.setPaidFull(true);
		orderVo.setAddress(add.getsDetailAddress());
		orderVo.setPhone(add.getsMobilePhone());
		orderVo.setPostCode(add.getsPostCode());
		orderVo.setTelephone(add.getsTelphone());
		orderVo.setReceiveName(add.getsRecipient());

		orderVo.setLeaveWord("尽快发货");
		// 是否是预售订单
		orderVo.setPreSale(false);
		orderVo.setAutoCancelOrderHours(BigDecimal.ONE);
		// 订单运费
		orderVo.setFreight(new BigDecimal(new Random().nextInt(50) + 10));

		List<OrderItemVo> orderItemVoList = new ArrayList<OrderItemVo>();

		orderItemVoList.add(getDefaultOrderItemVo());

		// 构造默认的请求 OrderItem
		orderVo.setOrderItems(orderItemVoList);

		return orderVo;

	}

	/**
	 * 
	 * 构造默认商品 OrderItemVo
	 * 
	 */

	public static OrderItemVo getDefaultOrderItemVo() {
		OrderItemVo orderitem = new OrderItemVo();
		// 预售商品
		orderitem.setPreSale(false);
		// psp 商品
		orderitem.setPspProduct(false);

		orderitem.setCatalogId(TestDataManager.getRandomUUID().toString());
		orderitem.setProductNum(new Random().nextInt(5) + 1);

		orderitem.setProductName("自动化测试商品+" + TestDataManager.getRandomNum(10));
		orderitem.setPriceType(PriceTypeEnum.QuotePrice);
		orderitem.setProductId(TestDataManager.getRandomUUID().toString());

		BigDecimal price = new BigDecimal(new Random().nextInt(50) + 30);

		orderitem.setEarnestPrice(price);
		orderitem.setProductPrice(price);
		orderitem.setOriginalPrice(price);
		// 直播
		orderitem.setSalesType(SalesTypeEnum.AlreadyInStock);

		orderitem.setLogisticsType(logisticsType);
		orderitem.setProductRefundChannel(ProductRefundChannelEnum.Official);
		orderitem.setBrandId(5);
		orderitem.setPackageNo("");
		orderitem.setFirstCategoryId(111111111);
		orderitem.setSecondCategoryId(22222222);
		orderitem.setThirdCategoryId(33333333);
		orderitem.setStockStatus(StockStatusEnum.Spot);
		orderitem
				.setProductDetailInfo("e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男");
		orderitem.setProductRecordNo("1234567");
		orderitem.setProductRefundChannel(ProductRefundChannelEnum.Official);
		orderitem
				.setProperty("06f25e0c-e431-44ae-8a07-4d0bc824e3bd#尺寸:951a814e-2ded-4241-b9a0-91b2cd9a44fd#6,d2f663ea-3214-4344-abce-a8eaffcc43ce#颜色:f3ed3ad7-a084-450b-b698-256542963306#红色");
		orderitem
				.setPictureUrl("http://pic1.ymatou.com/G01/shangou/M00/39/85/rBBlD1k-U5eAMqEfAAIULSyYXWM521_104_78_n_w_o.jpg");

		return orderitem;

	}

	/**
	 * 
	 * 构造默认的下单请求bean， 一个订单一个商品默认使用平台券，商家券
	 * 
	 */
	public static PlaceOrderReq getDefaultOrderReq() {

		PlaceOrderReq placeorderBean = new PlaceOrderReq();

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));

		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId2"));

		/*		YmatouCouponVo ymtCoupon = new YmatouCouponVo();

				// 平台优惠券
				BigDecimal couponValue = new BigDecimal(13);

				String couponCode = null;

				try {

					couponCode = new OrderCallService().receivePlatformCoupon(userId,
							couponValue);

					ymtCoupon.setApplianceType(YmatouCouponApplianceTypeEnum.ALL);
					ymtCoupon.setCouponCode(couponCode);
					ymtCoupon.setCouponValue(couponValue);

				} catch (Exception e1) {
					// TODO Auto-generated catch block
					Logger.debug("创建领取平台优惠券失败！");
					// e1.printStackTrace();
				}*/

		placeorderBean.setYmatouCoupon(null);

		/*	placeorderBean.setYmatouCoupon(ymtCoupon);

			if (null == couponCode || couponCode.isEmpty()) {
				placeorderBean.setYmatouCoupon(null);
			}*/

		placeorderBean.setAppId("AutoTest");

		placeorderBean.setUserId(userId);
		placeorderBean.setRequestId(String.valueOf(System.currentTimeMillis()));
		placeorderBean.setTerminalSource(TerminalSourceEnum.IOS);
		placeorderBean.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		placeorderBean.setDeviceId("af0888f9-2a1e-4162-a240-39c26ef05ed6");

		placeorderBean.setNeedsReduceStock(false);

		OrderGroupVo groupVo1 = getDefaultOrderGroupVo(userId, sellerId);

		ArrayList<OrderGroupVo> orderGroupVoList = new ArrayList<OrderGroupVo>();

		orderGroupVoList.add(groupVo1);

		placeorderBean.setOrderSource(OrderSourceEnum.PC);

		placeorderBean.setOrderGroups(orderGroupVoList);

		return placeorderBean;
	}

	public static PlaceOrderReq getDefaultOrderReq(Integer userId) {

		PlaceOrderReq placeorderBean = new PlaceOrderReq();

		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		YmatouCouponVo ymtCoupon = new YmatouCouponVo();

		// 平台优惠券
		BigDecimal couponValue = new BigDecimal(13);

		String couponCode = null;
		try {
			couponCode = new OrderCallService().receivePlatformCoupon(userId,
					couponValue);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			Logger.debug("创建平台优惠券失败！");
			e1.printStackTrace();
		}

		ymtCoupon.setApplianceType(YmatouCouponApplianceTypeEnum.ALL);
		ymtCoupon.setCouponCode(couponCode);
		ymtCoupon.setCouponValue(couponValue);
		placeorderBean.setAppId("AutoTest");
		placeorderBean.setYmatouCoupon(ymtCoupon);

		if (null == couponCode || couponCode.isEmpty()) {
			placeorderBean.setYmatouCoupon(null);
		}

		placeorderBean.setUserId(userId);
		placeorderBean.setRequestId(TestDataManager.getRandomUUID().toString());
		placeorderBean.setTerminalSource(TerminalSourceEnum.IOS);
		placeorderBean.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		placeorderBean.setDeviceId("af0888f9-2a1e-4162-a240-39c26ef05ed6");

		List<OrderGroupVo> groups = new ArrayList<OrderGroupVo>();
		OrderGroupVo groupVo1 = getDefaultOrderGroupVo(userId, sellerId);

		groups.add(groupVo1);

		placeorderBean.setOrderSource(OrderSourceEnum.PC);

		placeorderBean.setOrderGroups(groups);

		return placeorderBean;
	}
	/**
	 * 
	 * 创建用余额支付订单
	 * 
	 */
	public static PlaceOrderResp payOrder() {

		PlaceOrderResp placeOrderResp = placeOrderWithOutCoupon();

		int userId = placeOrderResp.getUserId();

		int tradingId = placeOrderResp.getTradingId();

		BigDecimal price = placeOrderResp.getPayAmount();

		new OrderCallService().orderPayRequest(userId, price, tradingId);

		return placeOrderResp;

	}

	public static PlaceOrderResp payOrder(Integer userId) {

		PlaceOrderResp placeOrderResp = placeOrderWithOutCoupon(userId);

		int tradingId = placeOrderResp.getTradingId();

		BigDecimal price = placeOrderResp.getPayAmount();

		new OrderCallService().orderPayRequest(userId, price, tradingId);

		return placeOrderResp;

	}

	public static PlaceOrderResp payOrder(Integer userId, String type) {

		PlaceOrderResp placeOrderResp = placeOrderWithOutCoupon(userId);

		int tradingId = placeOrderResp.getTradingId();

		BigDecimal price = placeOrderResp.getPayAmount();

		new OrderCallService().orderPayRequest(userId, price, tradingId, type);

		return placeOrderResp;

	}

	/**
	 * 
	 * 支付前取消订单
	 * 
	 */
	public static PlaceOrderResp cancelOrderBeforePaid(CancelOrderTypeEnum type) {

		PlaceOrderResp placeOrderResp = placeOrderWithOutCoupon();

		int userId = placeOrderResp.getUserId();

		new OrderCallService().cancelOrder(placeOrderResp.getOrderList().get(0)
				.getOrderId(), userId, type);

		return placeOrderResp;

	}

	/**
	 * 
	 * 支付后取消订单
	 * 
	 */
	public static PlaceOrderResp cancelOrderAfterPaid(CancelOrderTypeEnum type) {

		PlaceOrderResp placeOrderResp = payOrder();

		int userId = placeOrderResp.getUserId();

		new OrderCallService().cancelOrder(placeOrderResp.getOrderList().get(0)
				.getOrderId(), userId, type);

		return placeOrderResp;

	}

	/**
	 * 
	 * 买手接单
	 * 
	 */
	public static PlaceOrderResp acceptOrder() {

		PlaceOrderResp placeOrderResp = payOrder();

		int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
		int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

		new OrderCallService().acceptOrder(orderId, sellerId);

		return placeOrderResp;

	}

	/*
	 * 码头保存发货物流单号
	 * */

	public static void saveDeliverSummary(Integer orderId, int sellerId,
			String billCode) {

		try {
			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(billCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"CatalogStatus\":\"7\",\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":true,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());
			Logger.comment("发货处理");
			SaveDeliverSummaryCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	/**
	 * 
	 * 买手发货
	 * 
	 */
	public static PlaceOrderResp dispatchedOrder() {

		PlaceOrderResp placeOrderResp = acceptOrder();

		int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
		int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

		String billCode = new OrderCallService().dispatchedByXlobo(orderId,
				sellerId);

		placeOrderResp.getOrderList().get(0).setBillCode(billCode);

		return placeOrderResp;

	}

	/**
	 * 
	 * 确认收货
	 * 
	 */
	public static PlaceOrderResp confirmReceiveOrder() {

		PlaceOrderResp placeOrderResp = dispatchedOrder();

		int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
		int userId = placeOrderResp.getUserId();

		new OrderCallService().confirmReceive(userId, orderId);

		return placeOrderResp;

	}

	public static void main(String args[]) {

		PlaceOrderService.placeOrder9();

	}
}
